package com.zxy.javaarithmetic.chapter_1_StackQueue;

import java.util.ArrayDeque;
import java.util.Queue;

/*
 *  @项目名：  study
 *  @包名：    com.zxy.javaarithmetic.chapter_1_StackQueue
 *  @文件名:   P_4_CatDogQueue
 *  @创建者:   zhangxy
 *  @创建时间:  2018/12/3 11:13
 *  @描述：    实现一种猫狗队列结构
 */
public class P_4_CatDogQueue {

	public static void main(String[] args) {
		CatDogQueue queue = new CatDogQueue();
		for (int i = 0; i < 15; i++) {
			int random = (int) (1 + Math.random() * 100);
			if (random % 2 == 0) {
				queue.add(new Cat());
			} else {
				queue.add(new Dog());
			}
		}
		while (!queue.isEmpty()) {
			System.out.print(queue.pollAll().getType() + " ");
		}
	}

	public static class Pet {

		private String type;

		public Pet(String type) {
			this.type = type;
		}

		public String getType() {
			return type;
		}
	}

	public static class Cat extends Pet {
		public Cat() {
			super("cat");
		}
	}

	public static class Dog extends Pet {
		public Dog() {
			super("dog");
		}
	}

	/**
	 * 包装类
	 */
	private static class PetEnterQueue {
		private Pet pet;
		private int count;

		public PetEnterQueue(Pet pet, int count) {
			this.pet = pet;
			this.count = count;
		}

		public Pet getPet() {
			return pet;
		}

		public int getCount() {
			return count;
		}
	}

	public static class CatDogQueue {

		private Queue<PetEnterQueue> queueDog;
		private Queue<PetEnterQueue> queueCat;
		private int count;

		public CatDogQueue() {
			queueCat = new ArrayDeque<>();
			queueDog = new ArrayDeque<>();
		}

		public void add(Pet pet) {
			PetEnterQueue petEnterQueue = new PetEnterQueue(pet, ++count);
			if (pet instanceof Cat) {
				queueCat.add(petEnterQueue);
			} else if (pet instanceof Dog) {
				queueDog.add(petEnterQueue);
			}
		}

		public Pet pollAll() {
			if (isEmpty()) {
				throw new RuntimeException("queue is empty");
			} else if (!isEmptyDog() && !isEmptyCat()) {
				return queueCat.peek().count < queueDog.peek().count ? queueCat.poll()
					.getPet() : queueDog.poll().getPet();
			} else if (!isEmptyCat()) {
				return queueCat.poll().getPet();
			} else {
				return queueDog.poll().getPet();
			}

		}

		public Pet pollDog() {
			if (!queueDog.isEmpty()) {
				return queueDog.poll().getPet();
			}
			return null;
		}

		public Pet pollCat() {
			if (!queueCat.isEmpty()) {
				return queueCat.poll().getPet();
			}
			return null;
		}

		public boolean isEmpty() {
			return queueCat.isEmpty() && queueDog.isEmpty();
		}

		public boolean isEmptyCat() {
			return queueCat.isEmpty();
		}

		public boolean isEmptyDog() {
			return queueDog.isEmpty();
		}

		@Override
		public String toString() {
			return queueCat.toString() + "----" + queueDog.toString();
		}

	}

}
